#!/usr/bin/env node

const https = require('https'),
      http  = require('http'),
      cheerio = require('cheerio'),
      fs = require('fs'),
      url = require('url'),
      addr = 'https://trade.maoyan.com/films?showType=3',
      dataArr = [],
      log  = console.log;
let html = fs.readFileSync('./index.html').toString('utf8');
let opt = url.parse(addr);

opt.headers = {
  'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
};

https.get(opt, (res)=>{
  let data = '';

  res.on('data',(chunck)=>{
    data += chunck;
  });

  res.on('end',()=>{
    log('end');
    let $ = cheerio.load(data);
    let id = $('body').find('div.movie-item-title>a');
    let title = $('body').find('div.movie-item-title');
    let grade = $('body').find('div.channel-detail-orange');
   
    for(let i=0; i<title.length; i++){
      let length = $(id[i]).attr('data-val').length;
      let name = $(title[i]).attr('title');
      let id1 = ($(id[i]).attr('data-val')).slice(9,length-1);
      let range = $(grade[i]).text().trim();
      dataArr[i]={movieId:id1,movieName:name,movieRange:range};
      //log(dataArr[i]);
      //log();
    }
    log(dataArr);
  });

});

http.createServer((req,res)=>{
  let addr = url.parse(req.url);
  if(addr.pathname == '/'){
    res.writeHead(200,{
      'Content-Type':'text/html',
      'Content-Length':Buffer.byteLength(html)
    });

    res.end(html);

  }else if(addr.pathname == '/getlist'){
    res.writeHead(200,{
      'Content-Type':'application/json',

    });
    res.end(JSON.stringify(dataArr));
  }
  else{
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>Not Found!</h1>');
    return;
  }
}).listen(8080);
